package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.entity.PageBean;
import com.itheima.entity.PageQueryObject;
import com.itheima.entity.Student;
import com.itheima.mapper.StudentMapper;
import com.itheima.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;

@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentMapper studentMapper;

    @Override
    public PageBean search(PageQueryObject pageQueryParam) {
        PageHelper.startPage(pageQueryParam.getPage(),pageQueryParam.getPageSize());
        Page results = (Page) studentMapper.search(pageQueryParam);
        return new PageBean(results.getTotal(),results.getResult());
    }

    @Override
    public void delete(Integer[] ids) {
        studentMapper.delete(ids);
    }

    @Override
    public void save(Student student) {
        student.setCreateTime(LocalDate.now());
        student.setUpdateTime(LocalDate.now());
        student.setViolationScore(0);
        student.setViolationCount(0);
        studentMapper.insert(student);
    }

    @Override
    public Student getById(Integer id) {
        return studentMapper.selectById(id);
    }

    @Override
    public void update(Student student) {
        student.setUpdateTime(LocalDate.now());
        studentMapper.update(student);
    }

    @Transactional
    @Override
    public void updateViolation(Integer id, Integer score) {
//        直接调用其他接口的sql语句获取当前id学生对象
        Student student = studentMapper.selectById(id);
        student.setViolationScore(score);
//        非常细节
        if (student.getViolationCount() == null) {
            student.setViolationCount(1);
        } else {
            student.setViolationCount(student.getViolationCount() + 1);
        }
//        直接调用其他接口的sql语句
        studentMapper.update(student);


    }
}
